<?php
class toRedis
{
  //将access表信息写入87上redis 14库
  public $conn=null;

  /**
    * 链接数据库
    * @param $db 要链接的数据库
    */
  public function connect($db){
    // $this->conf=Conf::getIns();
    $conn=mysqli_connect('139.129.207.87','pcm','pcm=pwd@2016');
    $res=mysqli_query($conn,"use $db");
     mysqli_query($conn,'set names utf8');
     $this->conn=$conn;
  }
  /**
   * 执行sql查询
   * @param $sql 要执行的sql语句
   */
  public function query($sql){
    $rs=mysqli_query($this->conn,$sql);
    return $rs;
  }

  /**
   * 查询所有需要的数据
   * @param $sql 要执行的sql文件
   */
  public function getAll($sql){
    $rs=$this->query($sql);
    $data=array();
    while($row=mysqli_fetch_assoc($rs)){
      $data[]=$row;
    }
    return $data;
  }

  /**
   * 查询数据库中数据
   * 只获取usr和mac
   */
   public function getUser(){
     $arr=[];
     $this->connect('devinfo');
     $sql="select usr,mac from accessuser";
     $data=$this->getAll($sql);

     //循环处理数组，让mac做key
     foreach ($data as $k=>$v) {
       $arr[strtolower(str_replace('-','',$v['mac']))]=$v['usr'];
     }
     return $arr;
   }

   /**
    * 将处理出的数组处理写入redis
    *
    */
    public function setRedis(){
      $redis=new Redis();
      $data=$this->getUser();
      $redis->connect('r-m5e0b5bc32613094.redis.rds.aliyuncs.com','6379');
      $redis->auth("REDISpwd2016");
      $redis->select(14);
      $redis->hmset('accessuser',$data);
    }

    /**
     * 从redis中读取数据
     *
     */
     public function getRedis(){
       $redis=new Redis();
       $redis->connect('r-m5e0b5bc32613094.redis.rds.aliyuncs.com','6379');
       $redis->auth("REDISpwd2016");
       $redis->select(14);
       $data=$redis->hmget('accessuser',array('DC-41-5F-E0-14-21'));
       print_r($data);
     }

     /**
      * 将请求的mac 和手机号写入redis
      * @param $mac mac地址
      * @param $tel 手机号
      */
      public function mactoRedis(){
        $mac=$_POST['usermac'];
        $tel=$_POST['usertel'];
        $redis=new Redis();
        $redis->connect('r-m5e0b5bc32613094.redis.rds.aliyuncs.com','6379');
        $redis->auth("REDISpwd2016");
        $redis->select(14);
        $redis->hmset('accessuser',[$mac=>$tel]);
      }
}
$toRedis=new toRedis();
$toRedis->mactoRedis();
 ?>
